<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.rechargeInfo" placeholder="充值账号" clearable></el-input>
      </el-form-item>
      <el-select v-model="dataForm.status" placeholder="请选择订单状态">
        <el-option
          v-for="item in orderStatus"
          :key="item.key"
          :label="item.value"
          :value="item.key">
        </el-option>
      </el-select>
      <el-form-item>
        <span class="demonstration">起始时间</span>
        <el-date-picker
          v-model="dataForm.begin"
          type="datetime"
          placeholder="选择日期时间"
          format='yyyy-MM-dd HH:mm:ss'
          default-time="12:00:00">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <span class="demonstration">结束时间</span>
        <el-date-picker
          v-model="dataForm.end"
          type="datetime"
          placeholder="选择日期时间"
          format='yyyy-MM-dd HH:mm:ss'
          default-time="12:00:00">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="excelHandle()">导出Excel</el-button>
        <!--<el-button v-if="isAuth('order:orderinfo:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>-->
        <!--<el-button v-if="isAuth('order:orderinfo:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>-->
        <el-button v-if="isAuth('order:orderinfo:update')" type="danger" @click="doSend()" :disabled="dataListSelections.length <= 0">发货</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        width="260"
        label="订单ID">
      </el-table-column>
      <el-table-column
        prop="orderSn"
        header-align="center"
        align="center"
        width="260"
        label="订单编号">
      </el-table-column>
      <el-table-column
        prop="userId"
        header-align="center"
        align="center"
        label="用户">
      </el-table-column>
      <el-table-column
        prop="username"
        header-align="center"
        align="center"
        label="用户昵称">
      </el-table-column>
      <el-table-column
        prop="orderDesc"
        header-align="center"
        align="center"
        label="订单商品描述">
      </el-table-column>
      <el-table-column
        prop="rechargeInfo"
        header-align="center"
        align="center"
        label="用户信息">
      </el-table-column>
      <el-table-column
        prop="payAmount"
        header-align="center"
        align="center"
        width="100"
        label="付款金额">
      </el-table-column>
      <el-table-column
        prop="bill"
        header-align="center"
        align="center"
        width="150"
        label="发货单号">
      </el-table-column>

      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        width="100"
        label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" size="small" type="info">待付款</el-tag>
          <el-tag v-else-if="scope.row.status === 2" size="small" type="success">已付款</el-tag>
          <el-tag v-else-if="scope.row.status === 3" size="small" type="success">已发货</el-tag>
          <el-tag v-else-if="scope.row.status === 4" size="small" type="success">检查非自动</el-tag>
          <el-tag v-else-if="scope.row.status === 5" size="small" type="success">待退款</el-tag>
          <el-tag v-else-if="scope.row.status === 6" size="small" type="success">充值成功</el-tag>
          <el-tag v-else-if="scope.row.status === 7" size="small" type="success">已手动退款</el-tag>
          <el-tag v-else-if="scope.row.status === -1" size="small" type="info">已关闭</el-tag>
          <el-tag v-else-if="scope.row.status === -2" size="small" type="info">已退款</el-tag>
          <el-tag v-else-if="scope.row.status === -3" size="small" type="warn">提交异常</el-tag>
          <el-tag v-else-if="scope.row.status === -4" size="small" type="warn">支付状态异常</el-tag>
          <el-tag v-else-if="scope.row.status === -5" size="small" type="warn">请手动退款</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="rechargeType"
        header-align="center"
        align="center"
        width="80"
        label="充值类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.rechargeType === 1" size="small" type="success">自动</el-tag>
          <el-tag v-else-if="scope.row.rechargeType === 2" size="small" type="warn">手动</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="下单时间">
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './orderinfo-add-or-update'
  import Vue from 'vue'
  export default {
    data () {
      return {
        dataForm: {
          key: '',
          rechargeInfo: '',
          begin: '',
          end: '',
          status: ''
        },
        dataList: [],
        orderStatus: [
          {key: 1, value: '待付款'},
          {key: 2, value: '已付款'},
          {key: 3, value: '已发货'},
          {key: 4, value: '检查非自动'},
          {key: 5, value: '待退款'},
          {key: 6, value: '充值成功'},
          {key: 7, value: '已手动退款'},
          {key: -1, value: '已关闭'},
          {key: -2, value: '已退款'},
          {key: -3, value: '提交异常'},
          {key: -4, value: '支付状态异常'},
          {key: -5, value: '请手动退款'}
        ],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.dataForm.end = new Date()
      let today = new Date().getTime()
      let lastDay = this.getTimeByDay(today, -30)
      this.dataForm.begin = this.formatTime(lastDay)
      this.getDataList()
    },
    methods: {
      getTimeByDay (today, num) {
        return today + 60 * 60 * 1000 * 24 * num
      },
      formatTime (time) {
        return new Date(time)
      },
      // 获取数据列表
      getDataList () {
        if ((this.dataForm.key === null || this.dataForm.key === undefined || this.dataForm.key === '') &&
          ((this.dataForm.begin === null || this.dataForm.begin === undefined || this.dataForm.begin === '') ||
            (this.dataForm.end === null || this.dataForm.end === undefined || this.dataForm.end === ''))) {
          this.$alert('请填写查询条件')
          return
        }
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/order/orderinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key,
            'status': this.dataForm.status,
            'rechargeInfo': this.dataForm.rechargeInfo,
            'begin': this.dataForm.begin.format('yyyy-MM-dd hh:mm:ss'),
            'end': this.dataForm.end.format('yyyy-MM-dd hh:mm:ss')
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      excelHandle () {
        let url = window.SITE_CONFIG['baseUrl'] + '/order/orderinfo/queryExcel'
        let xhr = new XMLHttpRequest()
        xhr.open('post', url)
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
        xhr.setRequestHeader('token', Vue.cookie.get('token'))
        xhr.responseType = 'blob'
        var formData = this.$http.adornData({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'key': this.dataForm.key,
          'status': this.dataForm.status,
          'rechargeInfo': this.dataForm.rechargeInfo,
          'begin': this.dataForm.begin.format('yyyy-MM-dd hh:mm:ss'),
          'end': this.dataForm.end.format('yyyy-MM-dd hh:mm:ss')
        })
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const blob = new Blob([xhr.response])
            let url = window.URL.createObjectURL(blob)

            let link = document.createElement('a')
            link.href = url
            link.style.display = 'none'

            const fileName = decodeURI(xhr.getResponseHeader('content-disposition').split(';')[1].split('=')[1])
            link.setAttribute('download', fileName)
            link.click()
            window.URL.revokeObjectURL(url)
          }
        }
        xhr.send(formData)
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/order/orderinfo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      doSend (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$prompt('请填写发货单号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.$http({
            url: this.$http.adornUrl('/order/orderinfo/doSend?no=' + value),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }
</script>
